package com.ocom.wxapi.controller;


import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson.JSON;
import com.google.zxing.WriterException;
import com.ocom.common.entity.master.EntityMjQrList;
import com.ocom.common.request.wx.QrPageOnLoadRequest;
import com.ocom.common.request.wx.QrPagePollingQrCodeRequest;
import com.ocom.common.request.wx.UserAccessPageOnShowRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.wx.QrPageOnLoadResponse;
import com.ocom.common.utils.Base64Util;
import com.ocom.common.utils.QRCodeUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.wxapi.client.AccessClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@PreAuthorize("hasRole('ROLE_WX')")
@RequestMapping("/QrPage")
@RestController
public class QrPageController {


    @Autowired
    AccessClientService accessClientService;

    @PostMapping("/onLoad")
    public Result onShow(@Valid QrPageOnLoadRequest request) throws IOException, WriterException {
        Result result=accessClientService.newQrCode(request);


        QrPageOnLoadResponse qrPageOnLoadResponse=new QrPageOnLoadResponse();


        Map<String, String> pageFormat=new HashMap<>();
        pageFormat.put("pageTitle","设置二维码");
        qrPageOnLoadResponse.setPageFormat(pageFormat);
        qrPageOnLoadResponse.setHint("操作说明:xxx");
        if(result.getCode()==200){
        //    System.out.println(789);
        //    System.out.println(result);
            EntityMjQrList entityMjQrList= JSON.parseObject(JSON.toJSONString(result.getData()),EntityMjQrList.class);

            QrConfig config = new QrConfig(150, 150);
            // 设置边距，既二维码和背景之间的边距
            config.setMargin(0);
            // 设置前景色，既二维码颜色（青色）
//            config.setForeColor(Color.CYAN.getRGB());
            // 设置背景色（灰色）
//            config.setBackColor(Color.GRAY.getRGB());
            // 生成二维码到文件，也可以到流
            BufferedImage t= QrCodeUtil.generate(entityMjQrList.getQrCode(), config);
            qrPageOnLoadResponse.setQrCode(Base64Util.BufferedImageToBase64(t));

       }

        return ResultUtil.success(qrPageOnLoadResponse);
    }

    @PostMapping("/pollingQrCode")
    public Result pollingQrCode(@Valid QrPagePollingQrCodeRequest request) {
        Result result=accessClientService.pollingQrCode(request.getQrCode(),1);
        return result;
    }
}
